package com.cuitrip.business.invite;

import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.cuitrip.apiservice.BusinessHelper;
import com.cuitrip.apiservice.OrderBusiness;
import com.cuitrip.apiservice.UserBusiness;
import com.cuitrip.business.bill.AccountAddEvent;
import com.cuitrip.business.invite.InviteDetailFragment;
import com.cuitrip.business.invite.model.InviteInfo;
import com.cuitrip.business.login.LoginInstance;
import com.cuitrip.business.share.ShareChannelBuilder;
import com.cuitrip.business.share.model.ServiceShareObject;
import com.cuitrip.business.share.ui.ShareDialogFragment;
import com.cuitrip.business.webview.H5UrlMaker;
import com.cuitrip.component.item.CtTextView;
import com.cuitrip.service.R;
import com.cuitrip.util.SpanUtil;
import com.cuitrip.util.text.TextProxy;
import com.lab.app.customui.CustomUiConfig;
import com.lab.app.customui.CustomUiFragment;
import com.lab.image.process.MakeImageUtil;
import com.lab.jumper.FragmentJumper;
import com.lab.network.model.CtApiResponse;
import com.lab.network.model.IProxyCallback;
import com.lab.network.model.ProxyResult;
import com.lab.network.proxy.ApiProxy;
import com.lab.rx.bus.RxBus;
import com.lab.utils.DisplayUtil;
import com.lab.utils.SimpleCryptoUtils;
import com.lab.utils.ToastUtil;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.functions.Action1;

/**
 * Created by sheena on 16/5/18.
 */
public class InviteCodeFragment extends CustomUiFragment implements IProxyCallback{
    
    @Bind(R.id.tv_invite_num)
    CtTextView mInviteNumLayout;
    
    @Bind(R.id.tv_promotion_code)
    CtTextView mProCodeLayout;

    @Bind(R.id.tv_friends)
    CtTextView mFriends;

    @Bind(R.id.tv_invite_desc_num)
    CtTextView mInviteDesc;

    @Bind(R.id.desc)
    CtTextView mDesc;

    @Bind(R.id.tv_reward_desc)
    CtTextView mRewardDesc;

    private ShareDialogFragment shareDialogFragment;
    private ApiProxy mApiProxy=new ApiProxy(this);
    private int inviteNum;
    private String affiliateId;
    private String nick;
    private int money;

    @Override
    public boolean initCloseTopBar() {
        return false;
    }

    @Override
    public CustomUiConfig initCustomUiConfig() {
        CustomUiConfig customUiConfig = new CustomUiConfig();
        customUiConfig.mTopbarMiddleAreaName = getString(R.string.user_invite_detail_title);
        customUiConfig.mLeftStyle = CustomUiConfig.AreaStyle.ICON_STYLE;
        customUiConfig.mTopbarLeftAreaName = getString(R.string.back_icon);
        customUiConfig.mRightStyle = CustomUiConfig.AreaStyle.TEXT_STYLE;
        customUiConfig.mTopbarRightAreaName = getString(R.string.operation_view_detail);
        return customUiConfig;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return super.onCreateView(inflater, container, savedInstanceState, R.layout.fragment_invite_code_page);
    }

    @Override
    public void initData() {
        showLoading();
        UserBusiness.getInviteInfo(mApiProxy);
        if (isAdded()) {
            RxBus.getDefault().toObservable().subscribe(new Action1<Object>() {
                @Override
                public void call(Object o) {
                    if (o instanceof InviteEvent) {
                        showLoading();
                        UserBusiness.getInviteInfo(mApiProxy);
                    }

                }
            });
        }
        nick = LoginInstance.getInstance().getUserInfo().getNick();
    }

    @OnClick(R.id.fl_invite_layout)
    public void invite() {
        File file = screenShot();
        String path = file.getAbsolutePath();
        String title = getString(R.string.user_invite_share_title,nick);
        String content = getString(R.string.user_invite_share_content,nick);
        ServiceShareObject shareObject = ServiceShareObject.newInstance("1", title, path, content, H5UrlMaker.getInsiderInviteShare(affiliateId,Uri.encode(nick)));
        if (shareDialogFragment != null && shareDialogFragment.isShowing()) {
            return;
        }
        shareDialogFragment = ShareDialogFragment.newInstance(shareObject, ShareChannelBuilder.TripShareChannel.INVITE_CODE, MakeImageUtil.takeScreenShot(getHostActivity()));
        showDialogFragment(shareDialogFragment);

    }

    @Override
    public void initView() {
        ButterKnife.bind(this, getView());
    }

    @Override
    public void onTopbarLeftPress() {
        getHostActivity().finish();
    }

    @Override
    public void onTopbarRightPress() {
        InviteDetailFragment inviteDetailFragment = InviteDetailFragment.newInstance(inviteNum,money);
        FragmentJumper.addFragment(getHostActivity().getCustomSelfFragmentManager(), R.id.container,inviteDetailFragment , InviteDetailFragment.class.getName(), true);
    }

    private File screenShot() {
        View view = getHostActivity().getLayoutInflater().inflate(R.layout.invite_share_view, null);
        TextView shareInvite= (TextView) view.findViewById(R.id.tv_share_invite);
        shareInvite.setText(getString(R.string.user_invite_share_signup,nick));
        MakeImageUtil.layoutView(view, DisplayUtil.dip2px(500.f),DisplayUtil.dip2px(400.f));
        Bitmap bitmap = MakeImageUtil.convertViewToBitmap(view);
        String path = getHostActivity().getCacheDir().getAbsolutePath();
        File file = MakeImageUtil.saveBitmap(path, bitmap, "shareshot.jpg");
        return file;
    }


    @Override
    public boolean onProxyResult(ProxyResult<?> result) {
        CtApiResponse response= (CtApiResponse) result.getData();
        if (response.isResponseNormal()){
            if(response.result instanceof InviteInfo){
                InviteInfo inviteInfo= (InviteInfo) response.result;
                inviteNum = inviteInfo.getInviteNum();
                affiliateId = inviteInfo.getAffiliateId();
                money = inviteInfo.getMoney();
                if (inviteNum==0){
                    mDesc.setVisibility(View.VISIBLE);
                    mInviteDesc.setVisibility(View.INVISIBLE);
                    mInviteNumLayout.setVisibility(View.INVISIBLE);
                    mFriends.setVisibility(View.INVISIBLE);
                    mTopbarRightArea.setVisibility(View.GONE);
                }else{
                    mDesc.setVisibility(View.GONE);
                    mInviteDesc.setVisibility(View.VISIBLE);
                    mInviteDesc.setText(getString(R.string.user_invite_number_3));
                    mInviteNumLayout.setVisibility(View.VISIBLE);
                    mInviteNumLayout.setText(String.valueOf(inviteNum));
                    mFriends.setVisibility(View.VISIBLE);
                    mFriends.setText(TextProxy.getInstance().formatWithSingleAndMore(inviteNum,R.string.user_invite_number_5,R.string.user_invite_number_4));
                }
                mProCodeLayout.setText(affiliateId);
                mRewardDesc.setText(getString(R.string.user_invite_rule, money));
            }
        }else {
            if (!TextUtils.isEmpty(response.msg)){
                ToastUtil.toast(getHostActivity(),response.msg,0);
            }
        }
        hideLoading();
        return false;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}
